package com.example.housebiz.service;

import com.example.housebiz.mapper.AgencyMapper;
import com.example.housecommon.model.Agency;
import com.example.housecommon.model.User;
import com.example.housecommon.page.PageData;
import com.example.housecommon.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-05-26
 **/
@Service
public class AgencyService {


    @Autowired
    private AgencyMapper agencyMapper;



    @Value("${img.prefix}")
    private String imgPrefix;


    public List<Agency> getAllAgency() {
        return agencyMapper.select(new Agency());
    }


    /**
     * 访问user表获取详情 添加用户头像
     *
     * @param userId
     * @return
     */
    public User getAgentDetail(Long userId) {
        User user = new User();
        user.setId(userId);
        user.setType(2);
        List<User> userList = agencyMapper.selectAgent(user, PageParams.build(1,1));
        setImg(userList);
        if(!userList.isEmpty()) {
            User agent = userList.get(0);
            //将经纪人关联的经纪机构也查询出来
            Agency agency = new Agency();
            agency.setId(agent.getAgencyId().intValue());
            List<Agency> agencies = agencyMapper.select(agency);
            if(!agencies.isEmpty()) {
                agent.setAgencyName(agencies.get(0).getName());
            }
            return agent;
        }
        return null;
    }

    private void setImg(List<User> list) {
        list.forEach(i -> {
            i.setAvatar(imgPrefix + i.getAvatar());
        });

    }

    public PageData<User> getAllAgent(PageParams pageParams) {
        List<User> agents = agencyMapper.selectAgent(new User(),pageParams);
        setImg(agents);
        Long count = agencyMapper.selectAgentCount(new User());
        return PageData.buildPage(agents,count,pageParams.getPageSize(),pageParams.getPageNum());
    }

}

